<template>
  <el-dialog
      v-model="visible"
      :close-on-click-modal="false"
      :title="title"
      :type="type"
      center
      width="48%"
      top="50px"
      class="group-dialog"
      @close="handleClose"
  >
    <div class="add-dialog-component">
      <el-alert
          :style="{ backgroundColor: '#fff' }"
          title="保存后将生效在移动端的分类里"
          type="info"
          :closable="false"
      />

      <!-- 简化的表单结构 -->
      <div class="form-content">
        <el-form :model="formData" label-width="100px">
          <el-form-item label="分类名称">
            <el-input
                v-model="formData.classifyName"
                maxlength="6"
                placeholder="请输入分类名称（最大6个字符）"
                style="width: 300px"
            />
          </el-form-item>

          <el-form-item label="分类图片">
            <el-upload
                :headers="headers"
                :data="dataObj"
                :multiple="false"
                :show-file-list="false"
                :on-success="handleImageSuccess"
                class="upload-uploader"
                action="/api/file/upload"
            >
              <img
                  v-if="formData.classifyImage"
                  width="80"
                  height="80"
                  :src="formData.classifyImage"
              />
              <el-icon v-else class="upload-icon">
                <el-icon-plus />
              </el-icon>
            </el-upload>
          </el-form-item>
        </el-form>
      </div>

      <div class="add-btn-wrap">
        <template v-if="isCheck">
          <el-button
              class="add"
              type="primary"
              @click="close"
          >确定
          </el-button>
        </template>
        <template v-else>
          <el-button
              type="primary"
              @click="onSubmit"
          >保存
          </el-button>
        </template>
      </div>
    </div>
  </el-dialog>
</template>
<script setup>
import { Plus as ElIconPlus } from '@element-plus/icons-vue'
import {
  addCommodityClass,
  getCommodityClassById,
  updateCommodityClass,
  updateCommodityClass1
} from '@/api/commodityClassApi'
import { computed, ref, watch } from 'vue';
import { ElMessage } from 'element-plus'

const props = defineProps({
  dialogVisible: {
    type: Boolean,
    default: false
  },
  type: {
    type: String,
    default: 'add'
  },
  params: {
    type: Object,
    default: () => ({})
  }
})

const formData = ref({
  classifyName: '',
  classifyImage: '',
  parentId: '',
  id: ''
})

const headers = ref({
  Authorization: '',
})

const dataObj = ref({
  folderId: 1,
})

const isSubmitting = ref(false)
const visible = computed({
  get () {
    return props.dialogVisible
  },
  set (val) {
    if (!val) {
      handleClose()
    }
    emit('update:dialogVisible', val)
  }
})

const title = computed(() => {
  const stateMap = {
    add: '添加分类',
    edit: '编辑分类',
    check: '查看分类',
  }
  return stateMap[props.type]
})

const isCheck = computed(() => {
  return props.type === 'check'
});

// 监听params变化，自动设置表单数据
watch(() => props.params, (newParams) => {
  if (newParams && Object.keys(newParams).length > 0) {
    setParams(newParams)
  }
}, { immediate: true })

function handleImageSuccess(response, file, fileList) {
  const url = response.data.url
  formData.value.classifyImage  = url
}

const emit = defineEmits(['close', 'success', 'update:dialogVisible'])

function handleClose() {
  formData.value = {
    categoryName: '',
    categoryImg: '',
    parentId: '',
    id: ''
  }
  isSubmitting.value = false
  emit('close')
}

// 监听params变化时的赋值修改
watch(() => props.params, (newParams) => {
  if (newParams && Object.keys(newParams).length > 0) {
    if (newParams.isAdd) {
      // 添加模式
      formData.value = {
        classifyName: '',  // 改为classifyName
        classifyImage: '', // 改为classifyImage
        parentId: newParams.parentId,
        id: ''
      }
    } else {
      // 编辑模式（从index.vue接收的数据直接赋值）
      formData.value = {
        classifyName: newParams.classifyName || '',  // 对应index.vue的classifyName
        classifyImage: newParams.classifyImage || '', // 对应index.vue的classifyImage
        parentId: newParams.parentId || '',
        id: newParams.id || ''
      }
    }
  }
}, { immediate: true })
async function setParams(params) {
  try {
    // 添加模式
    if (params && params.isAdd) {
      formData.value.parentId = params.parentId
      formData.value.categoryName = ''
      formData.value.categoryImg = ''
      return
    }

    // 编辑模式
    if (params && params.id) {
      const res = await getCommodityClassById({ oneClassifyId: params.id })
      if (res && res.data) {
        const data = res.data
        formData.value.categoryName = data.classifyName || ''
        formData.value.categoryImg = data.classifyImage || ''
        formData.value.id = data.classifyId || data.id || ''
      }
    }
  } catch (error) {
    console.error('获取数据失败:', error)
    ElMessage.error('获取数据失败')
  }
}

function onSubmit() {
  if (props.params.isAdd) {
    addGroup()
  } else {
    updateGroup()
  }
}

async function addGroup() {
  if (isSubmitting.value) return
  isSubmitting.value = true

  try {
    if (!formData.value.classifyName.trim()) {
      ElMessage.error('请输入分类名称')
      isSubmitting.value = false
      return
    }

    if (!formData.value.classifyImage) {
      ElMessage.error('请上传分类图片')
      isSubmitting.value = false
      return
    }
   const requestData = {
      classifyName: formData.value.classifyName,
      classifyImage: formData.value.classifyImage,
      parentId: formData.value.parentId
    }

    const res = await updateCommodityClass1(requestData)

    if (res && res.code === '200') {
      ElMessage.success('添加成功')
      emit('success')
      setTimeout(() => {
        visible.value = false
      }, 500)
    } else {
      throw new Error(res.message || '添加失败')
    }
  } catch (error) {
    console.error('添加失败:', error)
    ElMessage.error(error.message || '添加失败')
  } finally {
    isSubmitting.value = false
  }
}

async function updateGroup() {
  if (isSubmitting.value) return
  isSubmitting.value = true

  try {
    if (!formData.value.classifyName.trim()) {
      ElMessage.error('请输入分类名称')
      isSubmitting.value = false
      return
    }

    if (!formData.value.classifyImage) {
      ElMessage.error('请上传分类图片')
      isSubmitting.value = false
      return
    }
    const requestData = {
      id: formData.value.id,
      classifyName: formData.value.classifyName,
      classifyImage: formData.value.classifyImage
    }

    const res = await updateCommodityClass1(requestData)

    if (res && res.code === '200') {
      ElMessage.success('更新成功')
      emit('success')
      setTimeout(() => {
        visible.value = false
      }, 500)
    } else {
      throw new Error(res.message || '更新失败')
    }
  } catch (error) {
    console.error('更新失败:', error)
    ElMessage.error(error.message || '更新失败')
  } finally {
    isSubmitting.value = false
  }
}

defineExpose({ setParams })
</script>
<style lang="scss" scoped>
.group-dialog {
  .el-dialog {
    min-width: 500px;
    max-width: 600px;
  }
}

.add-dialog-component {
  padding: 15px 20px;

  .form-content {
    margin: 20px 0;

    .upload-uploader {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: border-color 0.3s;
      width: 80px;
      height: 80px;
      display: flex;
      align-items: center;
      justify-content: center;

      &:hover {
        border-color: #409eff;
      }

      .upload-icon {
        font-size: 28px;
        color: #8c939d;
      }

      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }
  }

  .add-btn-wrap {
    text-align: center;
    margin-top: 20px;
  }
}
</style>

